<template>
  <div style="width: 600px;">
    <h3 style="margin-bottom: 16px;">第一步，填写商品基本信息</h3>
    <Form :model="spuData" :label-width="90" :rules="spuFormRule" ref="spuForm">
      <FormItem label="商品标题：" prop="title">
        <Input v-model="spuData.title" placeholder="最多输入三十个字"/>
      </FormItem>
      <FormItem label="商品分类：" prop="selectClassify">
        <Select v-model="spuData.selectClassify" multiple>
          <i-option v-for="item in classifyTree" :value="item.id" :key="item.id">
            <span :class="{childItem: item.parentId}"></span>{{ item.name }}
          </i-option>
        </Select>
      </FormItem>
      <FormItem label="商品单位：" prop="goodsUnit">
        <ul class="list">
          <li class="add" @click="addUnit">+添加单位</li>
          <li v-for="(unit, index) in units" :key="index" @click="selectUnit(unit.id, unit.unit)" :class="{selected: spuData.goodsUnit === unit.id}">{{ unit.unit }}</li>
        </ul>
        <p><span style="color: #ff9900;">提示：</span>点击选中，但只能选中一个单位（该项为必选项）</p>
      </FormItem>
      <FormItem label="商品标签：">
        <ul class="list">
          <li class="add" @click="addLabel">+添加标签</li>
          <li v-for="(label, index) in labels" :key="index" @click="selectLabel(label.id, label.label)" :class="{selected: spuData.goodsLabel.indexOf(label.id) !== -1}">{{ label.label }}</li>
        </ul>
        <p><span style="color: #ff9900;">提示：</span>点击选中，可多选，但最多只能选两个标签，再次点击取消选中（该项不是必选项）</p>
      </FormItem>
      <FormItem label="商品备注：" prop="remark">
        <Input type="textarea" v-model="spuData.remark" placeholder="如，本商品进货来源：XX堂，电话：187xxxxxxxx...等信息（可以为空）"/>
      </FormItem>
      <FormItem label="商品权重：" prop="sortWeight">
        <Slider v-model="spuData.sortWeight" :tip-format="format" @on-change="valueChange"/>
        <p><span style="color: #ff9900;">提示：</span>权重决定商品在手机主页面的展示排序，权重值为0~100，默认为0，权重越高排序越靠前</p>
      </FormItem>
      <!--添加图片-->
      <FormItem label="商品图片：">
        <div style="overflow: hidden;">
          <div v-for="(src, index) in base64Data" :key="index" class="img_list">
            <img :src="src" alt="图片" width="58">
            <Icon type="close-circled" color="#ed3f14" size="16" @click="delImage(index)"></Icon>
          </div>
          <Upload
            v-show="base64Data.length < 5"
            ref="upload"
            :show-upload-list="false"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :before-upload="handleBeforeUpload"
            multiple
            type="drag"
            action="#"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="camera" size="20"></Icon>
            </div>
          </Upload>
        </div>
        <p><span style="color: #ff9900;">提示：</span>图片大小不超过5M，至少一张图片，最多5张图片，建议使用方形图片</p>
      </FormItem>
      <FormItem label="是否新品：" prop="isNew">
        <i-switch size="large" true-value="1" false-value="0" v-model="spuData.isNew">
          <span slot="open">开启</span>
          <span slot="close">关闭</span>
        </i-switch>
      </FormItem>
      <FormItem label="是否推荐：" prop="isRecommend">
        <i-switch size="large" true-value="1" false-value="0" v-model="spuData.isRecommend">
          <span slot="open">开启</span>
          <span slot="close">关闭</span>
        </i-switch>
      </FormItem>
      <FormItem label="是否清仓：" prop="isClear">
        <i-switch size="large" true-value="1" false-value="0" v-model="spuData.isClear">
          <span slot="open">开启</span>
          <span slot="close">关闭</span>
        </i-switch>
      </FormItem>
    </Form>
    <div class="btn">
      <Button type="primary" @click="nextStep">下一步完善sku信息</Button>
    </div>
    <image-util :fixed-number="[1, 1]" @cropImg="cropImg" ref="crop"></image-util>
  </div>
</template>

<script>
import imageUtil from '../../common/imageUtil'
export default {
  name: 'spu-step',
  components: {
    imageUtil
  },
  data () {
    return {
      // spu信息
      spuData: {
        title: '',
        goodsLabel: [],
        goodsUnit: '',
        selectClassify: [],
        remark: '',
        isNew: '0',
        isRecommend: '0',
        isClear: '0',
        sortWeight: 0
      },

      // 单位，标签，分类
      units: [],
      labels: [],
      classifyTree: [],
      unitsName: '',
      labelsName: [],

      // 图片数据
      base64Data: [],
      blobData: [],

      // 规则
      spuFormRule: {
        title: [
          { required: true, message: '商品标题不能为空', trigger: 'blur' }
        ],
        selectClassify: [
          { required: true, message: '商品分类不能为空', trigger: 'change', type: 'array', min: 1 }
        ],
        goodsUnit: [
          { required: true, message: '商品单位不能为空', trigger: 'change', type: 'number' }
        ]
      }
    }
  },
  methods: {
    format (val) {
      /*
      * 商品权重格式化提示
      * */
      return val
    },
    valueChange (val) {
      /*
      * 商品权重发生改变提示当前排名百分比
      * */
      this.$ajax.get('/goods/manage/real/time/sort/weight', {params: {sortWeight: val}})
        .then(res => {
          if (res.data.success) {
            this.$Message.info('当前权重超过' + res.data.data * 100 + '%的商品')
          }
        })
    },

    selectUnit (id, unit) {
      /*
      * 点击单位触发，获取id保存
      * */
      this.spuData.goodsUnit = id
      this.unitsName = unit
    },
    selectLabel (id, label) {
      /*
      * 点击标签触发
      * 1、最多两个，
      * 2、检查是否已有，是：取消，否：小于两个选中，大于两个不做处理
      * */
      let index = this.spuData.goodsLabel.indexOf(id)
      if (index !== -1) {
        this.spuData.goodsLabel.splice(index, 1)
        this.labelsName.splice(index, 1)
      } else if (this.spuData.goodsLabel.length < 2) {
        this.labelsName.push(label)
        this.spuData.goodsLabel.push(id)
      }
    },

    handleBeforeUpload (e) {
      /*
      * 图片上传调用切图
      * */
      this.$refs.crop.setImage({e, name: 'spu'})
      return false
    },
    cropImg (data) {
      /*
      * 图片剪切完成之后回调方法
      * data包括图片信息（展示信息：imgTime, 提交信息：blob）
      * */
      this.base64Data.push(data.imgTime)
      this.blobData.push(data.blob)
    },

    delImage (index) {
      /*
      * 删除图片，两个地方需要删除base64Data, blobData
      * */
      this.$Modal.confirm({
        title: '删除图片',
        content: '你确认删除该图片吗？',
        onOk: () => {
          this.base64Data.splice(index, 1)
          this.blobData.splice(index, 1)
        }
      })
    },

    addUnit () {
      let value = ''
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              autofocus: true,
              placeholder: '输入商品单位，如：个、件、套...'
            },
            on: {
              input: (val) => {
                value = val
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post('/goods/manage/add/unit/page', {unit: value}).then((res) => {
            if (res.data.success) {
              this.units.push({
                id: res.data.data.id,
                unit: res.data.data.unit
              })
              this.$Message.success('添加成功，请再次选择')
            }
          })
        }
      })
    },
    addLabel () {
      let value = ''
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              autofocus: true,
              placeholder: '输入商品标签，如：古典、时尚、热卖...'
            },
            on: {
              input: (val) => {
                value = val
              }
            }
          })
        },
        onOk: () => {
          this.$ajax.post('/goods/manage/add/label/page', {label: value}).then((res) => {
            if (res.data.success) {
              this.labels.push({
                id: res.data.data.id,
                label: res.data.data.label
              })
              this.labelInput = false
              this.$Message.success('添加成功，请再次选择')
            }
          })
        }
      })
    },

    nextStep () {
      /*
      * 进入下一步
      * 1、校验填写信息是否正确
      * 2、信息正确通知父组件进入下一步
      * */
      this.$refs.spuForm.validate((valid) => {
        if (valid && this.spuData.goodsUnit && this.blobData[0]) {
          let classify = []
          this.classifyTree.forEach(item => {
            if (this.spuData.selectClassify.indexOf(item.id) !== -1) {
              classify.push(item.name)
            }
          })
          let data = {
            classify: classify.join('，'),
            units: this.unitsName,
            labels: this.labelsName.join('，')
          }
          this.$emit('getSpuData', {spuData: this.spuData, images: this.base64Data, blobs: this.blobData, data})
        } else {
          if (!this.spuData.title) {
            this.$Message.error('标题不能为空')
          }
          if (!this.spuData.selectClassify[0]) {
            this.$Message.error('分类不能为空')
          }
          if (!this.spuData.goodsUnit) {
            this.$Message.error('单位不能为空')
          }
          if (!this.blobData[0]) {
            this.$Message.error('必须要有一张图片')
          }
        }
      })
    },

    clearData () {
      /*
      * 清除本页数据
      * 1、表单数据
      * 2、图片数据
      * */
      this.$refs.spuForm.resetFields()
      this.spuData.goodsLabel = []
      this.labelsName = []
      this.spuData.goodsUnit = ''
      this.base64Data = []
      this.blobData = []
    }
  },
  created () {
    /*
    * 发请求得到标签，单位，分类
    * */
    this.$ajax.get('/goods/manage/get/category/unit/label/list').then((res) => {
      this.labels = res.data.data.goodsLabelList
      this.units = res.data.data.goodsUnitList
      res.data.data.goodsCategoryTreeList.forEach((item, index) => {
        this.classifyTree.push(item)
        this.classifyTree.push(...item.childCategoryList)
      })
    })
  }
}
</script>

<style scoped>
  .list{
    overflow: hidden;
  }
  .list li{
    float: left;
    height: 28px;
    line-height: 28px;
    margin-right: 20px;
    margin-bottom: 10px;
    border: 1px solid #dddee1;
    padding: 0 10px;
    border-radius: 3px;
    cursor: pointer;
  }
  .list li.selected{
    background-color: #2d8cf0;
    color: #fff;
  }
  .list li.add{
    border: 1px dashed #dddee1;
  }
  .list li.add:hover{
    color: #2d8cf0;
    border: 1px dashed #2d8cf0;
  }
  .btn{
    text-align: center;
    border-top: 1px solid #dddee1;
    padding-top: 16px;
  }
  .childItem{
    padding-left: 10px;
  }
  .img_list{
    float: left;
    margin-right: 10px;
    position: relative;
  }
  .img_list i{
    position: absolute;
    top: 4px;
    right: 4px;
    cursor: pointer;
  }
</style>
